package controlador;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.bd.exception.DAOException;
import modelo.dominio.Cliente;
import modelo.servicio.Clientes;

public class ClienteControlador extends HttpServlet {

    //private String html;
    private StringBuilder codigo;
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=ISO-8859-1");
        PrintWriter out = response.getWriter();
        String accion = request.getParameter("ac") == null ? "" : request.getParameter("ac");
        codigo = new StringBuilder();
        try {
            if (accion.compareToIgnoreCase("ca") == 0) {
                generarOpc(request.getSession().getAttribute("sUsuario").toString());
                out.println(codigo.toString());
                response.flushBuffer();
            } else if (accion.compareToIgnoreCase("ls") == 0) {
                List<Cliente> clientes = Clientes.instancia().obtener(request.getSession().getAttribute("sUsuario").toString());
                request.setAttribute("clientes", clientes);
                getServletContext().getRequestDispatcher("/front?v=3&ac=4").forward(request, response);
            }
        } catch (Exception ex) {
            out.println(ex.getMessage());
        } finally {
            out.close();
        }
    }

// <editor-fold defaultstate="collapsed" desc="Metodos HttpServlet. Click en el signo + izquierdo para editar el codigo.">
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
// </editor-fold>

    private void generarOpc(String login) {
        codigo.append("<select name='cmb_cliente' id='cmb_cliente'>")
                         .append("<option value='NA'>Ninguno</option>");
        try {
            List<Cliente> clientes = Clientes.instancia().obtener(login);
            if (!clientes.isEmpty()) {
                for (Cliente cl : clientes) {
                    codigo.append("<option value='").append(cl.getNumero()).append("'>")
                            .append(cl.getRazonSocial())
                            .append("</option>");
                }
            }
            codigo.append("</select>");
            codigo.append("<script type=\"text/javascript\">")
                    .append("$('#cmb_cliente').change(function() {")
                    .append("var singleValues = $('#cmb_cliente').val();")
                    .append("charge('#pnl_facturas', 'fact?ac=ls&cmb_cliente='+singleValues);")
                    .append("});")
                    .append("</script>");
        } catch (DAOException ex) {
            codigo.append("Error al generar los clientes: ")
                    .append(ex.getMessage());
        }
    }
}
